package com.myStoreorderProvider.service.impl;

import cn.hutool.core.lang.Snowflake;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.myStoreorderProvider.mapper.MyStoreorderMapper;
import com.myStoreorderProvider.utils.UtilSnowflake;
import entity.*;
import jdk.net.SocketFlow;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.ResponseBody;
import service.mystore.MyStoreorderService;
import util.CropStringUtil;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;


/**
 * 我的门店订单service
 * @author oahner
 * @create 2022-04-16 15:45
 */
@Service
@EnableTransactionManagement
public class MyStoreorderServiceImpl implements MyStoreorderService {

    private Logger logger = Logger.getLogger(getClass());

    @Autowired
    private MyStoreorderMapper mapper;

    @Resource
    private UtilSnowflake snowflake;


    /**
     * 获取我的门店订单列表
     * @param outorderPage
     * @return
     */
    @Override
    public ResponseMessage getMyOutorder(Map<String,Object> outorderPage) {
        logger.info("MyStoreorderServiceImpl getMyOutorder params:outorderPage="+outorderPage);
        ResponseMessage msg = new ResponseMessage();
        msg.setFlag(false);
        msg.setCode(StatusCode.ERROR);
        Outorder outorder = null;
        Integer pageNum = 1;
        try {
            //拆解Map，分别获取订单对象和分页参数
            if(null!=outorderPage.get("outorder")){
                outorder = JSONObject.parseObject(JSONObject.toJSONString(outorderPage.get("outorder")), Outorder.class);
                outorder = (Outorder) CropStringUtil.cropString(outorder);
            }
            if(null!=outorderPage.get("pageNum") && (Integer)outorderPage.get("pageNum")>0){
                pageNum = (Integer) outorderPage.get("pageNum");
            }
            if(null != outorder && null!=outorder.getsId() && !"".equals(outorder.getsId())){
                PageHelper.startPage(pageNum,5);
                List<Outorder> myOutorder = mapper.getMyOutorder(outorder);
                if(myOutorder.size()>0){
                    PageInfo<Outorder> pageOrder = new PageInfo<Outorder>(myOutorder);
                    msg.setCode(StatusCode.OK);
                    msg.setFlag(true);
                    msg.setData(pageOrder);
                    msg.setMessage("get order success");
                    logger.debug("MyStoreorderServiceImpl getMyOutorder success result:msg="+msg);
                }else{
                    msg.setMessage("get order empty");
                    logger.debug("MyStoreorderServiceImpl getMyOutorder empty result:msg="+msg);
                }
            }else{
                msg.setMessage("get order fail");
                logger.debug("MyStoreorderServiceImpl getMyOutorder fail result:msg="+msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            msg.setMessage("get order error");
            logger.error("MyStoreorderServiceImpl getMyOutorder error param:msg="+msg);
        }
        return msg;
    }

    /**
     * 获取我的门店订单详情
     * @param outorderinfo
     * @return
     */
    @Override
    public ResponseMessage getMyOutorderInfo(Outorderinfo outorderinfo) {
        logger.info("MyStoreorderServiceImpl getMyOutorderInfo params:outorder="+outorderinfo);
        ResponseMessage msg = new ResponseMessage();
        msg.setFlag(false);
        msg.setCode(StatusCode.ERROR);
        try {
            if(null != outorderinfo && null!=outorderinfo.getoId() && !"".equals(outorderinfo.getoId())){
                List<Outorderinfo> myOutorderinfo = mapper.getMyOutorderInfo(outorderinfo);
                if(myOutorderinfo.size()>0){
                    msg.setCode(StatusCode.OK);
                    msg.setFlag(true);
                    msg.setData(myOutorderinfo);
                    msg.setMessage("get orderinfo success");
                    logger.debug("MyStoreorderServiceImpl getMyOutorderInfo success result:msg="+msg);
                }else{
                    msg.setMessage("get orderinfo empty");
                    logger.debug("MyStoreorderServiceImpl getMyOutorderInfo empty result:msg="+msg);
                }
            }else{
                msg.setMessage("get orderinfo fail");
                logger.debug("MyStoreorderServiceImpl getMyOutorderInfo fail result:msg="+msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            msg.setMessage("get orderinfo error");
            logger.error("MyStoreorderServiceImpl getMyOutorderInfo error param:msg="+msg);
        }
        return msg;
    }


    /**
     * 签收我的订单
     * @param outorder
     * @return
     */
    @Override
    public ResponseMessage signMyOutorder(Outorder outorder) {
        logger.info("MyStoreorderServiceImpl getMyOutorderInfo params:outorder="+outorder);
        ResponseMessage msg = new ResponseMessage();
        msg.setFlag(false);
        msg.setCode(StatusCode.ERROR);
        try {
            //判断订单号是否存在
            if(null != outorder && !"".equals(outorder.getOrderNum())){
                outorder.setStatus(4);
                outorder.setUpdateUser("RENHAO");
                int updateRow = mapper.updateMyOutorder(outorder);
                if(updateRow > 0){
                    msg.setCode(StatusCode.OK);
                    msg.setFlag(true);
                    msg.setData(updateRow);
                    msg.setMessage("sgin order success");
                    logger.debug("MyStoreorderServiceImpl signMyOutorder success result:msg="+msg);
                }else{
                    msg.setMessage("sgin order empty");
                    logger.debug("MyStoreorderServiceImpl signMyOutorder empty result:msg="+msg);
                }
            }else{
                msg.setMessage("sgin order fail");
                logger.debug("MyStoreorderServiceImpl signMyOutorder fail result:msg="+msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            msg.setMessage("sgin order error");
            logger.error("MyStoreorderServiceImpl signMyOutorder error param:msg="+msg);
        }
        return msg;
    }

    /**
     * 我的订单支付
     * @param outorder
     * @return
     */
    @Override
    public ResponseMessage payMyOutorder(Outorder outorder) {
        logger.info("MyStoreorderServiceImpl payMyOutorder params:outorder="+outorder);
        ResponseMessage msg = new ResponseMessage();
        msg.setFlag(false);
        msg.setCode(StatusCode.ERROR);
        try {
            //判断订单号是否存在
            if(null != outorder && !"".equals(outorder.getOrderNum())){
                outorder.setStatus(1);
                outorder.setUpdateUser("RENHAO");
                int updateRow = mapper.updateMyOutorder(outorder);
                if(updateRow > 0){
                    msg.setCode(StatusCode.OK);
                    msg.setFlag(true);
                    msg.setData(updateRow);
                    msg.setMessage("pay order success");
                    logger.debug("MyStoreorderServiceImpl payMyOutorder success result:msg="+msg);
                }else{
                    msg.setMessage("pay order empty");
                    logger.debug("MyStoreorderServiceImpl payMyOutorder empty result:msg="+msg);
                }
            }else{
                msg.setMessage("pay order fail");
                logger.debug("MyStoreorderServiceImpl payMyOutorder fail result:msg="+msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            msg.setMessage("pay order error");
            logger.error("MyStoreorderServiceImpl payMyOutorder error param:msg="+msg);
        }
        return msg;
    }

    /**
     * 获取商品分类
     * @return
     */
    @Override
    public ResponseMessage getProductCategory() {
        logger.info("MyStoreorderServiceImpl getProduct1Category init============");
        ResponseMessage msg = new ResponseMessage();
        msg.setFlag(false);
        msg.setCode(StatusCode.ERROR);
        try {
            //获取商品分类（1级，2级，封装至一起）
            List<Map<String, Object>> productCategory = mapper.selProductCategory();
            if(productCategory.size() > 0){
                msg.setCode(StatusCode.OK);
                msg.setFlag(true);
                msg.setData(productCategory);
                msg.setMessage("get productCategory success");
                logger.debug("MyStoreorderServiceImpl getProduct1Category success result:msg="+msg);
            }else{
                msg.setMessage("get productCategory empty");
                logger.debug("MyStoreorderServiceImpl getProduct1Category empty result:msg="+msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            msg.setMessage("get productCategory error");
            logger.error("MyStoreorderServiceImpl getProduct1Category error param:msg="+msg);
        }
        return msg;
    }


    /**
     * 根据分类获取商品
     * @param productPage
     * @return
     */
    @Override
    public ResponseMessage getProductByCategory(Map<String,Object> productPage) {
        logger.info("MyStoreorderServiceImpl getProductByCategory params:productPage="+productPage);
        ResponseMessage msg = new ResponseMessage();
        msg.setFlag(false);
        msg.setCode(StatusCode.ERROR);
        Product product = null;
        Integer pageNum = 1;
        try {
            //拆解Map，分别获取订单对象和分页参数
            if(null!=productPage.get("product")){
                product = JSONObject.parseObject(JSONObject.toJSONString(productPage.get("product")), Product.class);
                product = (Product) CropStringUtil.cropString(product);
            }
            if(null!=productPage.get("pageNum") && (Integer)productPage.get("pageNum")>0){
                pageNum = (Integer) productPage.get("pageNum");
            }
            //截取对象中长度大于50的字符串属性
            product = (Product) CropStringUtil.cropString(product);
            PageHelper.startPage(pageNum,5);
            List<Product> products = mapper.selProductByCategory(product);
            if(products.size() > 0){
                PageInfo<Product> pageInfo = new PageInfo<Product>(products);
                msg.setCode(StatusCode.OK);
                msg.setFlag(true);
                msg.setData(pageInfo);
                msg.setMessage("get product success");
                logger.debug("MyStoreorderServiceImpl getProductByCategory success result:msg="+msg);
            }else{
                msg.setMessage("get product empty");
                logger.debug("MyStoreorderServiceImpl getProductByCategory empty result:msg="+msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            msg.setMessage("get product error");
            logger.error("MyStoreorderServiceImpl getProductByCategory error param:msg="+msg);
        }
        return msg;
    }

    /**
     * 下单（订单和详情）
     * @param order
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public ResponseMessage addStoreOrder(Map<String, Object> order) {
        logger.info("MyStoreorderServiceImpl addStoreOrder params:order="+order);
        ResponseMessage msg = new ResponseMessage();
        msg.setFlag(false);
        msg.setCode(StatusCode.ERROR);
        Outorder outorder = null;
        List<Outorderinfo> oiList = null;
        //生成雪花ID
        String snow = String.valueOf(snowflake.getSnowflakeId());
        try {
            //拆解Map，分别获取订单对象和订单详情集合对象
            if(null!=order.get("outorder")){
                outorder = JSONObject.parseObject(JSONObject.toJSONString(order.get("outorder")), Outorder.class);
                outorder = (Outorder) CropStringUtil.cropString(outorder);
                outorder.setUpdateUser("RENHAO");
                outorder.setCreateUser("RENHAO");
                outorder.setOrderNum(snow);
            }
            if(null!=order.get("outorderinfo")){
                oiList = (List) order.get("outorderinfo");
                for(int i=0;i<oiList.size();i++){
                    Outorderinfo outorderinfo =
                            JSONObject.parseObject(JSONObject.toJSONString(oiList.get(i)), Outorderinfo.class);
                    outorderinfo.setoId(snow);
                    outorderinfo.setId(String.valueOf(snowflake.getSnowflakeId()));
                    outorderinfo.setUpdateUser("RENHAO");
                    outorderinfo.setCreateUser("RENHAO");
                    Stock stock = new Stock();
                    stock.setProductId(outorderinfo.getpId());
                    stock.setStorehouseId(outorder.getStorehouseId());
                    Integer quantity = mapper.selProductStock(stock);
                    //判断商品库存
                    if(quantity<outorderinfo.getQuantity()){
                        msg.setMessage("add order exceed stock");
                        logger.debug("MyStoreorderServiceImpl addStoreOrder exceed stock result:order="+order);
                        return msg;
                    }
                    //判断商品限购
                    Product product = mapper.selProductMaxAndMin(outorderinfo.getpId());
                    if(outorderinfo.getQuantity()>product.getMaxNum()
                            || outorderinfo.getQuantity()<product.getMinNum()){
                        msg.setMessage("add order exceed product");
                        logger.debug("MyStoreorderServiceImpl addStoreOrder exceed product result:order="+order);
                        return msg;
                    }
                    oiList.set(i,outorderinfo);
                }
            }

            //插入订单信息
            int inOutorder = mapper.insertOutorder(outorder);
            //插入订单详情信息
            int inOutorderinfo = mapper.insertOutorderinfo(oiList);
            if(inOutorder > 0 && inOutorderinfo>0){
                msg.setCode(StatusCode.OK);
                msg.setFlag(true);
                msg.setData(inOutorder+","+inOutorderinfo);
                msg.setMessage("add order success");
                logger.debug("MyStoreorderServiceImpl addStoreOrder success result:msg="+msg);
            }else{
                msg.setMessage("add order fail");
                logger.debug("MyStoreorderServiceImpl addStoreOrder fail result:order="+order);
            }
        } catch (Exception e) {
            e.printStackTrace();
            msg.setMessage("add order error");
            logger.error("MyStoreorderServiceImpl addStoreOrder error param:order="+order);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return msg;
    }

    /**
     * 退货单
     * @param returnInfo
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public ResponseMessage addReturnOrder(Map<String, Object> returnInfo) {
        logger.info("MyStoreorderServiceImpl addReturnOrder params:returnInfo="+returnInfo);
        ResponseMessage msg = new ResponseMessage();
        msg.setFlag(false);
        msg.setCode(StatusCode.ERROR);
        Return returnOrder = null;
        Outorderinfo outorderinfo = null;
        try {
            //拆解Map，分别获取退货订单对象和原订单详情集合对象
            if(null!=returnInfo.get("returnOrder")){
                returnOrder = JSONObject.parseObject(JSONObject.toJSONString(returnInfo.get("returnOrder")), Return.class);
                returnOrder = (Return) CropStringUtil.cropString(returnOrder);
            }
            if(null!=returnInfo.get("outorderinfo")){
                outorderinfo = JSONObject.parseObject(JSONObject.toJSONString(returnInfo.get("outorderinfo")), Outorderinfo.class);
                outorderinfo = (Outorderinfo) CropStringUtil.cropString(outorderinfo);
            }
            if(null != returnOrder && !"".equals(returnOrder.getStoreId()) && null != returnOrder.getStoreId()
                    && !"".equals(returnOrder.getOrderNum()) && null != returnOrder.getOrderNum()
                    && null != outorderinfo
                    && !"".equals(outorderinfo.getoId()) && null != outorderinfo.getoId()
                    && !"".equals(outorderinfo.getId()) && null != outorderinfo.getId()) {
                //退货单数据设置（ID，状态）
                returnOrder.setId(String.valueOf(snowflake.getSnowflakeId()));
                returnOrder.setType(0);
                returnOrder.setUpdateUser("RENHAO");
                returnOrder.setCreateUser("RENHAO");
                //订单详情数据设置（状态）
                outorderinfo.setUpdateUser("RENHAO");
                outorderinfo.setStatus(1);
                //生成一个退货订单
                int ri = mapper.insertReturnOrder(returnOrder);
                //修改原订单的详情状态
                int oi = mapper.updateOutorderinfoStatus(outorderinfo);
                if (ri > 0 && oi>0) {
                    msg.setCode(StatusCode.OK);
                    msg.setFlag(true);
                    msg.setData(ri+","+oi);
                    msg.setMessage("add returnOrder success");
                    logger.debug("MyStoreorderServiceImpl addReturnOrder success result:msg=" + msg);
                } else {
                    msg.setMessage("add returnOrder fail");
                    logger.debug("MyStoreorderServiceImpl addReturnOrder fail result:returnInfo=" + returnInfo);
                }
            }else{
                msg.setMessage("add returnOrder fail params is null");
                logger.debug("MyStoreorderServiceImpl addReturnOrder fail params is null result:returnInfo=" + returnInfo);
            }
        } catch (Exception e) {
            e.printStackTrace();
            msg.setMessage("add returnOrder error");
            logger.error("MyStoreorderServiceImpl addReturnOrder error param:returnInfo="+returnInfo);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return msg;
    }

    /**
     * 增加门店账单
     * @param storebill
     */
    public void addStoreBill(Storebill storebill){
        logger.info("MyStoreorderServiceImpl addStoreBill params:storebill="+storebill);
        int i = 0;
        if(null != storebill && !StringUtils.isEmpty(storebill.getStoreId())){
            storebill.setId(String.valueOf(snowflake.getSnowflakeId()));
            storebill.setStatus(0);
            storebill.setInId("0");
            storebill.setOutId("1");
            storebill.setCreateUser("RENHAO");
            storebill.setUpdateUser("RENHAO");
            i = mapper.insertStoreBill(storebill);
        }
        logger.debug("MyStoreorderServiceImpl addStoreBill result:total="+i);
    }


}
